from tornado.web import RequestHandler
import pymysql
import base64
import uuid
import os
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
access_key = 'N_8YeN5vLOqLdZ7BDQ--JMXlg4AN_4X8GkWTVtOo'
secret_key = 'yZ4LlKY4PHjDvHi4l5-gFGn3iXDeDlR0o1Mwj6ca'
domin = 'http://pengjinyl.cn/'

def get_files(files):
    global access_key
    global secret_key
    file = files['img'][0]
    key = uuid.uuid1()
    filename = file.get('filename')
    upload_path = os.path.join(os.path.dirname(__file__), 'files')
    file_path = os.path.join(upload_path, filename)
    f = open(file_path, 'wb')
    f.write(file['body'])
    f.close()
    q = Auth(access_key, secret_key)
    bucket_name = 'xupeng-site'
    token = q.upload_token(bucket_name, key, 3600)
    ret, info = put_file(token, key, file_path)
    return ret['key']


def str_sql(str):
    return '\'' + str + '\''


class BaseHandler(RequestHandler):
    def initialize(self):
        self.con = pymysql.connect(
            host = 'localhost',
            port = 3306,
            user = 'root',
            password = 'lf0429MR',
            db = 'hspfb',
            charset = 'utf8'
        )
        self.db = self.con.cursor(pymysql.cursors.DictCursor)
    def check_admin(self):
        cookie = self.get_secure_cookie('sessionid')
        if bytes(self.query_sql('select adaccount from hs_config where id = 1')[0]['adaccount'], encoding = "utf8") == cookie:
            self.isadmin = True
        else:
            self.isadmin = False
            
    def check_user(self):
        cookie = self.get_secure_cookie('sessionid')
        try:
            self.userid = self.query_sql('select id from hs_user where openid = {0} or id = {0}'.format(int(cookie)))[0]['id']
        except:
            self.userid = None
        if self.userid:
            self.isuser = True
        else:
            self.isuser = False

    def query_sql(self, sql):
        self.db.execute(sql)
        return self.db.fetchall()

    def modify_sql(self, sql):
        try:
            for s in sql:
                self.db.execute(s)
            self.con.commit()
            return True
        except:
            return False

    def insert_sql(self, sql):
        try:
            for s in sql:
                self.db.execute(s)
            self.con.commit()
            return True
        except:
            return False
    def res_success(self, type, data = [], object = {}, code = 0, message = ''):
        res = dict(
            code = code,
            message = message,
            data = data,
            object = object
        )
        if type == 'query':
            res['message'] = '查询成功'
        elif type == 'insert':
            res['message'] = '新增成功'
        elif type == 'delete':
            res['message'] = '删除成功'
        elif type == 'modify':
            res['message'] = '修改成功'
        else:
            pass
        return res
    def res_error(self, type, code = 1, message = ''):
        res = dict(
            code = code,
            message = message
        )
        if type == 'query':
            res['message'] = '查询失败'
        elif type == 'insert':
            res['message'] = '新增失败'
        elif type == 'delete':
            res['message'] = '删除失败'
        elif type == 'modify':
            res['message'] = '修改失败'
        else:
            pass
        return res

class SHandler(BaseHandler):
    def prepare(self):
        self.check_admin()
        if self.isadmin:
            pass
        else:
            self.write(dict(
                code = 2,
                message = '未登录'
            ))
            self.finish()

class UserHandler(BaseHandler):
    def prepare(self):
        self.check_admin()
        self.check_user()
        print(self.userid)
        if self.isadmin or self.isuser:
            pass
        else:
            self.write(dict(
                code = 2,
                message = '未登录'
            ))
            self.finish()